package com.atguigu.gmall.web;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author: atguigu
 * @create: 2023-03-01 11:44
 */
@Controller
public class IndexController {


    @Autowired
    private ProductFeignClient productFeignClient;


    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 首页index渲染
     * 服务端给浏览器客户端响应渲染完毕html文档,浏览器展示
     *
     * @param model
     * @return
     */
    @GetMapping({"/", "/index.html"})
    public String index(Model model) {
        //todo 获取渲染首页-商品数据 将来为了提高首页数据渲染,必然调用多个服务feign接口 采用异步服务编排进行优化
        //todo 获取渲染首页-广告数据
        //获取渲染首页-分类数据
        List<JSONObject> list = productFeignClient.getBaseCategoryList();
        model.addAttribute("list", list);
        return "/index/index";
    }


    /**
     * 基于Thymeleaf模板引擎将渲染后静态页保存到磁盘
     *
     * @return
     */
    @ResponseBody
    @GetMapping("indexCreate")
    public Result createIndex() throws IOException {
        //1.参数一:Thymeleaf模板文件名称
        String tempalte = "/index/index";
        //2.参数二:上下文对象封装-模板所需要数据
        List<JSONObject> list = productFeignClient.getBaseCategoryList();
        Context context = new Context();
        context.setVariable("list", list);
        //3.参数三:写文件对象
        FileWriter fileWriter = new FileWriter("D:\\nginx-1.12.2\\html\\index.html");
        //4.生成html文件
        templateEngine.process(tempalte, context, fileWriter);
        return Result.ok();
    }

}
